<!-- systemSet -->
<template>
  <div class="Leaderboard content_box">
    <div class="header_row flex align-center flex-wrap" v-if="hasBtn('bord:query')">
      <div class="flex align-center m-r-2">
        <span class="tit_span nowarp">周期：</span>
        <el-select v-model="searchObj.TimeType" placeholder="请选择" clearable>
          <el-option v-for="item in cycleOptions" :key="item.Skey" :label="item.Svalue" :value="item.Skey">
          </el-option>
        </el-select>
      </div>

      <div class="flex align-center m-r-2">
        <span class="tit_span nowarp">类型：</span>
        <el-select v-model="searchObj.TypeName" placeholder="请选择" clearable>
          <el-option v-for="item in typeOptions" :key="item.Skey" :label="item.Svalue" :value="item.Skey">
          </el-option>
        </el-select>
      </div>
      <div class="flex align-center m-r-2">
        <span>时间：</span>
        <el-date-picker v-model="searchObj.timeValue" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable>
        </el-date-picker>
      </div>
      <el-button type="primary" @click="(searchObj.currentPage = 1), getListFun()">查询</el-button>
    </div>

    <div class="m-b-1 neck_box flex align-center space-between">
      <div>
        <el-button v-if="hasBtn('bord:add')" type="success" @click="showDialog('add')">新增数据</el-button>
        <!-- <el-button type="danger">批量删除</el-button> -->
        <el-button v-if="hasBtn('bord:export')" type="warning" disabled>导出列表</el-button>
      </div>
      <el-pagination background @current-change="handleCurrentChange" :current-page="searchObj.currentPage" :page-size="10" layout="total, prev, pager, next, jumper" :total="pageTotal">
      </el-pagination>
    </div>
    <el-table class="m-b-1" :data="tableData" border stripe style="width: 100%" v-loading="tableLoading" sortable="custom" @sort-change="sortChange">
      <el-table-column prop="index" label="序号" align="center" fixed>
      </el-table-column>
      <el-table-column label="周期" align="center" sortable>
        <template slot-scope="scope">{{scope.row.TimeType|translate}}</template>
      </el-table-column>
      <el-table-column label="类型" align="center" sortable>
        <template slot-scope="scope">{{scope.row.TypeName|translate}}</template>
      </el-table-column>
      <el-table-column prop="Target" label="上榜条件:销售额/个数" align="center" width="130" sortable>
      </el-table-column>
      <el-table-column label="奖励名额" align="center" sortable>
        <template slot-scope="scope">{{scope.row.Award + '个'}}</template>
      </el-table-column>
      <el-table-column label="奖励金额" align="center" sortable>
        <template slot-scope="scope">{{scope.row.Award + '元'}}</template>
      </el-table-column>
      <el-table-column label="第一名" width="140" align="center" sortable>
        <template slot-scope="scope">{{scope.row.RewardPlaces + '元'}}</template>
      </el-table-column>
      <el-table-column label="第二名" width="140" align="center" sortable>
        <template slot-scope="scope">{{scope.row.RewardPlaces + '元'}}</template>
      </el-table-column>
      <el-table-column label="第三名" width="140" align="center" sortable>
        <template slot-scope="scope">{{scope.row.RewardPlaces + '元'}}</template>
      </el-table-column>
      <el-table-column label="剩余名次" align="center" sortable>
        <template slot-scope="scope">{{scope.row.DecreaseRatio + '元'}}</template>
      </el-table-column>
      <!-- <el-table-column prop="StartTime" label="开始时间" width="180" align="center" sortable>
      </el-table-column>
      <el-table-column prop="EndTime" label="结束时间" width="180" align="center" sortable>
      </el-table-column> -->
      <el-table-column prop="Remark" label="活动规则" align="center" sortable>
      </el-table-column>

      <el-table-column label="是否有效" align="center" sortable>
        <template slot-scope="scope">
          <el-switch v-model="scope.row.IsActive" @change="switchChange(scope.row.Id, scope.row.IsActive)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" fixed="right" v-if="hasBtn('bord:delete') || hasBtn('bord:edit')">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)" v-if="hasBtn('bord:edit')" type="primary">编辑</el-button>

          <el-button v-if="hasBtn('bord:delete')" size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" destroy-on-close>
      <el-form ref="dataForm" :rules="rules" :model="addObj" label-position="right" label-width="140px">
        <el-form-item label="周期：" prop="TimeType">
          <el-select v-model="addObj.TimeType" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in cycleOptions" :key="item.Skey" :label="item.Svalue" :value="item.Skey" style="width: 100%">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="类型：" prop="TypeName">
          <el-select v-model="addObj.TypeName" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in typeOptions" :key="item.Skey" :label="item.Svalue" :value="item.Skey" style="width: 100%">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上榜条件:销售额额/个数" prop="Target">
          <el-input class="flex-1" v-model="addObj.Target" type="number"></el-input>
        </el-form-item>
        <el-form-item label="奖励名额：" prop="Award">
          <el-input class="flex-1" v-model="addObj.Award" min="0" type="number"><template slot="append">个</template></el-input>
        </el-form-item>
        <el-form-item label="奖励金额：" prop="Award">
          <el-input class="flex-1" v-model="addObj.Award" min="0" type="number"><template slot="append">元</template></el-input>
        </el-form-item>
        <el-form-item label="第一名：" prop="RewardPlaces">
          <el-input class="flex-1" v-model="addObj.RewardPlaces" type="number" min="0" @keyup.native="proving2($event)"><template slot="append">元</template></el-input>
        </el-form-item>
        <el-form-item label="第二名：" prop="RewardPlaces">
          <el-input class="flex-1" v-model="addObj.RewardPlaces" type="number" min="0" @keyup.native="proving2($event)"><template slot="append">元</template></el-input>
        </el-form-item>
        <el-form-item label="第三名：" prop="RewardPlaces">
          <el-input class="flex-1" v-model="addObj.RewardPlaces" type="number" min="0" @keyup.native="proving2($event)"><template slot="append">元</template></el-input>
        </el-form-item>
        <el-form-item label="剩余名次：" prop="RewardPlaces">
          <el-input class="flex-1" v-model="addObj.RewardPlaces" type="number" min="0" @keyup.native="proving2($event)"><template slot="append">元</template></el-input>
        </el-form-item>
        <!-- <el-form-item label="递减比例：" prop="DecreaseRatio">
          <el-input class="flex-1" v-model="addObj.DecreaseRatio" min="0" @keyup.native="proving2($event, '%')" type="number">
            <template slot="append">%</template>
          </el-input>
        </el-form-item> -->

        <el-form-item label="时间：" prop="timeValue">
          <el-date-picker v-model="addObj.timeValue" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable style="width: 100%">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="活动规则：" prop="Remark">
          <el-input type="textarea" class="flex-1" v-model="addObj.Remark" placeholder="请输入内容" maxlength="30" show-word-limit></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

  import { getList, save, deleteApi, valid } from '@/api/UserManage/Leaderboard'
  import { getCodeMasterList } from '@/api/system/dictionary'
  export default {
    //import引入的组件需要注入到对象中才能使用
    name: 'Leaderboard',
    components: {},
    data() {
      //这里存放数据
      return {
        tableLoading: false,
        dialogVisible: false,
        searchObj: {
          TimeType: "",
          TypeName: "",
          currentPage: 1,
          timeValue: ''
        },
        addObj: {
          "Id": "00000000-0000-0000-0000-000000000000",
          "TimeType": "", //周、月度、季度、年度等-数据字典设定
          "TypeName": "", //销售、拉新、推广等-数据字典设定
          "Target": 0, //目标金额/个数
          "Award": 0, //奖励金额
          "RewardPlaces": 0, //设定奖励多少名，如：前三名
          "DecreaseRatio": 0, //设定递减比例，第一名获得整体设定的奖励金额，第二名则获得整体设定的奖励金额递减百分比列，如：100 - （100*20%） = 80；
          // "StartTime": "", //开始时间
          // "EndTime": "", //结束时间
          "timeValue": "",
          "Remark": ""
        },
        SModuleOption: [],
        tableData: [
          { isActive: true }
        ],
        pageTotal: 0,
        tableLoading: false,
        dialogType: 'add',
        rules: {
          TimeType: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          TypeName: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          Target: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          Award: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          RewardPlaces: [{ required: true, message: '必填', trigger: 'blur' }],
          DecreaseRatio: [{ required: true, message: '必填', trigger: 'blur' }],
          timeValue: [{ required: true, message: '必填', trigger: 'blur' }]
        },
        cycleOptions: [],
        typeOptions: [],
      };
    },
    //监听属性 类似于data概念
    computed: {
      dialogTitle() {
        return this.dialogType == 'add' ? '新增数据' : '编辑数据'
      }
    },
    //监控data中的数据变化
    watch: {},
    filters: {
      translate(val) {
        if (val == 'week') {
          val = '自然周'
        }
        if (val == 'Year') {
          val = '自然年'
        }
        if (val == 'Month') {
          val = '自然月'
        }
        if (val == 'Quarter') {
          val = '季度'
        }
        if (val == 'Pull') {
          val = '激活榜'
        }
        if (val == 'Promotion') {
          val = '推广榜'
        }
        if (val == 'Sell') {
          val = '销售榜'
        }
        return val
      }
    },
    //方法集合
    methods: {
      switchChange(id, IsActive) {
        valid({ Id: id }).then(_ => {
          this.$notify({
            title: '切换成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.getListFun()
        })
      },
      showDialog(type) {
        if (type == 'add') {
          this.addObj = {
            "Id": "00000000-0000-0000-0000-000000000000",
            "TimeType": "", //周、月度、季度、年度等-数据字典设定
            "TypeName": "", //销售、拉新、推广等-数据字典设定
            "Target": 0, //目标金额/个数
            "Award": 0, //奖励金额
            "RewardPlaces": 0, //设定奖励多少名，如：前三名
            "DecreaseRatio": 0, //设定递减比例，第一名获得整体设定的奖励金额，第二名则获得整体设定的奖励金额递减百分比列，如：100 - （100*20%） = 80；
            "timeValue": "",
            "Remark": ""
          }
        }
        this.dialogType = type
        this.dialogVisible = true

      },
      saveData() {
        for (let item in this.addObj) {
          if (['Remark'].includes(item)) continue
          if (!this.addObj[item] && this.addObj[item] !== 'Number') {
            this.$notify({
              title: '提示',
              message: '请填写完整信息',
              type: 'warning',
              duration: 2000
            })
            return
          }
        }
        let addObj = this.$deepClone(this.addObj)
        addObj['StartTime'] = addObj.timeValue[0]//开始时间
        addObj['EndTime'] = addObj.timeValue[1]//结束时间
        delete addObj.timeValue
        save(addObj).then(res => {
          this.$notify({
            title: '保存成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.dialogVisible = false
          this.getListFun()
        }).catch(err => {

        })
      },
      handleCurrentChange(e) {
        this.searchObj.currentPage = e
        this.getListFun()
      },
      handleEdit(index, row) {
        console.log(row)
        this.addObj = {
          "Id": row.Id,
          "TimeType": row.TimeType, //周、月度、季度、年度等-数据字典设定
          "TypeName": row.TypeName, //销售、拉新、推广等-数据字典设定
          "Target": row.Target, //目标金额/个数
          "Award": row.Award, //奖励金额
          "RewardPlaces": row.RewardPlaces, //设定奖励多少名，如：前三名
          "DecreaseRatio": row.DecreaseRatio, //设定递减比例，第一名获得整体设定的奖励金额，第二名则获得整体设定的奖励金额递减百分比列，如：100 - （100*20%） = 80；
          // "StartTime": row.StartTime, //开始时间
          // "EndTime": row.EndTime, //结束时间
          "timeValue": [row.StartTime, row.EndTime],
          "Remark": row.Remark
        }
        this.showDialog('edit')
      },
      handleDelete(index, row) {
        this.$confirm('确认删除此条数据吗？').then(_ => {
          let obj = {
            Id: row.Id
          }
          deleteApi(obj).then(res => {

            this.$notify({
              title: '删除成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.tableData.splice(index, 1)
            this.pageTotal -= 1
          })
        })


      },
      sortChange(e) {
        let SortType = false
        if (e.order == "ascending") {
          SortType = true
        }
        this.getListFun(e.prop, SortType)
      },
      getListFun(SortName = 'CreateDate', SortType = true) {
        let currentPage = this.searchObj.currentPage
        this.tableLoading = true
        let searchObj = this.$deepClone(this.searchObj)
        let obj = {
          "TimeType": searchObj.TimeType, //	模块：指定整体管理模块设定
          "TypeName": searchObj.TypeName, //功能：指定整体管理模块下的某功能设定
          "IsPaging": true, //是否分页
          "SortName": SortName, //排序栏位
          "SortType": SortType,//排序类型｛True：正序；Flase：反序｝
          'PageIndex': currentPage
        }
        searchObj.timeValue && (obj['StartTime'] = searchObj.timeValue[0])//开始时间
        searchObj.timeValue && (obj['EndTime'] = searchObj.timeValue[1])//结束时间
        delete searchObj.timeValue
        getList(obj).then(res => {
          console.log(res.Data)
          if (!res.Data) {
            this.tableData = []
            this.pageTotal = 0
            this.tableLoading = false
            return
          }
          this.tableData = res.Data.map((item, index) => {
            for (let cell in item) {
              if (!item[cell] && this.$getType(item[cell]) !== 'Number') {
                item[cell] = '-'
              }
            }
            return { ...item, index: (index + 1) + ((currentPage - 1) * 10) }
          })
          this.pageTotal = res.Total
          this.tableLoading = false
        }).catch(_ => {
          this.tableLoading = false
          this.tableData = []
          this.pageTotal = 0
        })
      },

      //获取下拉数据
      getCodeMasterListFun() {
        let list = [
          { 'SModule': 'Leaderboard', 'SFunction': 'cycle' },
          { 'SModule': 'Leaderboard', 'SFunction': 'type' },
        ]
        list.forEach(item => {
          let obj = {
            "SModule": item.SModule,
            "SFunction": item.SFunction,
            "IsPaging": false, //是否分页
          }
          getCodeMasterList(obj).then(res => {
            console.log(res.Data)
            if (item.SFunction == 'cycle') {
              this.cycleOptions = res.Data
            } else {
              this.typeOptions = res.Data
            }
          })
        })

      }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.getCodeMasterListFun()
      this.getListFun()

    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {

    },
    beforeCreate() { }, //生命周期 - 创建之前
    beforeMount() { }, //生命周期 - 挂载之前
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroyed() { }, //生命周期 - 销毁完成
    activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>
//@import url(); 引入公共css类
<style  scoped>
  .Leaderboard .tit_span {
    width: 60px;
  }
</style>